<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue基础模板</title>
    <script src="../vue.js"></script>
</head>

<body>
    <div id="app">
        <input type="text" v-model="search">
        <ul>
            <li v-for="item in newPerson" :key="item.id">
                {{item.name}}-{{item.sex}}-{{item.age}}
            </li>
        </ul>
        <button @click="sortType=1">升序</button>
        <button @click="sortType=2">降序</button>
    </div>

    <script>
        Vue.config.productionTip = false;
        const vm = new Vue({
            el: "#app",
            data() {
                return {
                    search: '',
                    person: [
                        { id: '001', name: '周杰伦', sex: '男', age: 19 },
                        { id: '002', name: '邓伦', sex: '男', age: 24 },
                        { id: '003', name: '张杰', sex: '男', age: 35 },
                        { id: '004', name: '邓紫棋', sex: '女', age: 33 },
                        { id: '005', name: '林俊杰', sex: '男', age: 23 },
                        { id: '006', name: '周传雄', sex: '男', age: 21 },
                        { id: '007', name: '张惠妹', sex: '女', age: 36 }
                    ],
                    newPerson: [],
                    sortType: '0'
                }
            },
            watch: {
                search: {
                    //将过滤后的数据保存给新数组
                    immediate: true,
                    handler() {
                        this.newPerson = this.person.filter(item => item.name.includes(this.search))
                    }
                },
                sortType: {
                    //通过监听sortType的改变，重新渲染数据
                    immediate: true,
                    handler() {
                        this.newPerson.sort((a, b) => {
                            switch (this.sortType) {
                                case 1:
                                    return a.age - b.age
                                case 2:
                                    return b.age - a.age
                            }
                        })
                    }

                }
            }
        })
    </script>
</body>

</html>